﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class BuletinAnalyse : SessionPageBase
{
	public int lastDomainCount = 0;
	public string strPacientName, strPacientAge, strPacientSex, strMedicName;
	public string strPacientCNP, pacientID, strPacientSection, strClass, lstDomainID; //restrictions on domain class and id

	private bool bPrint, bDuplicat, bFullPrint;

	protected void Page_Load(object sender, EventArgs e)
    {
		if (EnsureNotCached()) return;
		try
        {
			LoadData();
			if (!IsPostBack)
			{
				printNotAllowed.Visible = !bPrint;
				txtDuplicat.Visible = bDuplicat && bFullPrint;
				txtForPrint.Visible = bPrint;
				txtForView.Visible = !txtForPrint.Visible;
				txtPrintDate.Visible = bPrint;
				txtViewDate.Visible = !txtPrintDate.Visible;
			}
		}
        catch (Exception ex)
        {
			message.Font.Bold = true;
			AppendWarningMessage(ex.ToString());
			//this.SetMessage(ex.Message, true); // <-- add DisplayMessage in the js first
        }
    }

	private bool EnsureNotCached()
	{
		//if (Request.QueryString["unique"] == null)
		//{
		//    //Response.Clear
		//    Response.Redirect(strFullUrl + "&unique=" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"));
		//    return true;
		//}
		return false;
	}

	private void CreateErrorMessage(string text)
	{
		message.ForeColor = System.Drawing.Color.Red;
		message.Font.Bold = true;
		message.Text = text;
	}
	private void AppendWarningMessage(string text)
	{
		message.ForeColor = System.Drawing.Color.Red;
		message.Font.Italic = true;
		if (message.Text.Length > 0)
			message.Text += "<br/>";
		message.Text += text;
	}

	/// <summary>
	/// Loads the information needed to display the page
	/// </summary>
	private void LoadData()
	{
		#region Load parameters
		intCodeID.Text = Request.QueryString["requestID"];
		int test;
		if (!int.TryParse(intCodeID.Text, out test)) // || !bool.TryParse(Request.QueryString["bPrint"], out bPrint)
		{
			CreateErrorMessage("Parametrii incorecti.");
			//TODO: javascript that redirects to LabRequest in 42 seconds.
			return;
		}
		if (!bool.TryParse(Request.QueryString["bPrint"], out bPrint))
			bPrint = false;
		strClass = Request.QueryString["class"];
		lstDomainID = Request.QueryString["lstDomainID"];
		#endregion

		#region Section
		// Load the section. If not in query string, use LRequest's section
		string strSection;
		if (!string.IsNullOrEmpty(Request.QueryString["section"]))
			strSection = Request.QueryString["section"];
		else
		{
			// The section was not provided, get it from lab_sections:
			//strSection = GetData("select SectionCode from LAB_SECTIONS where RequestID = " + intCodeID.Text)
			//    .Tables[0].Rows[0][0].ToString();
		}
		#endregion

		#region Gender and Age
		DataSet dsGenderAge = GetData(@"SELECT P.Sex, datediff(YY, P.BirthDate, GetDate()) as Age FROM PACIENTS P 
			WHERE P.[ID]=(SELECT PacientID from Lab_Requests L where L.[ID]=" + intCodeID.Text + ")");
		if ((dsGenderAge.Tables.Count > 0) && (dsGenderAge.Tables[0].Rows.Count > 0))
		{
			DataRow data = dsGenderAge.Tables[0].Rows[0];
			strPacientAge = data["Age"].ToString();
			try
			{
				strPacientSex = System.Convert.ToBoolean(data["Sex"]) ? "M" : "F";
			}
			catch (Exception ex)
			{
				AppendWarningMessage("Warning: Cannot convert db object '" + data["Sex"].ToString() +
					"' to bool: (" + ex.GetType().ToString() + ") " + ex.Message);
			}
		}
		else
		{
			strPacientAge = "--";
			strPacientSex = "N/A";
		}
		#endregion

		#region get more details, possibly including the payment type and the pregnacy status
		//TODO: move to a "Laboratory_AnalyseFileDetails" stored proc
		string sqlDetails = @"SELECT MedicName=s2.FirstName + ' ' + s2.LastName, convert(varchar(20),l.requestedDate,13) as RequestedDate, L.PaymentTypeID, L.IsPregnant,
			l.SectionCode,
			ISNULL(sec.Name,(SELECT top 1 Name FROM Sections WHERE Code like l.SectionCode)) as SectionName,
			s.FirstName + ' '+ s.LastName + ISNULL(' - '+s.Title,'') as RequestorName,
			p.LastName+ ' ' + p.FirstName as PacientName, p.CNP, p.id as pacientID, nrchit
			FROM Lab_Requests L
			LEFT JOIN staff s on l.requestorid=s.id
			LEFT JOIN pacients p on l.pacientid=p.id
			LEFT JOIN staff s2 on l.medicid=s2.id
			LEFT JOIN Sections sec ON sec.Code = p.CISection
			where L.[ID]=" + intCodeID.Text;
		DataSet dsDetails = null;
		try
		{
			dsDetails = GetData(sqlDetails);
		}
		catch (SqlException ex)
		{
			AppendWarningMessage("Warning: Cannot get some details <!-- " + sqlDetails + @" -->
				from the db: (" + ex.GetType().ToString() + ") " + ex.Message);
		}
		if ((dsDetails != null) && (dsDetails.Tables.Count > 0) && (dsDetails.Tables[0].Rows.Count > 0))
		{
			DataRow data = dsDetails.Tables[0].Rows[0];
			//strSectionRequest = data["SectionCode"];
			//strPaymentTypeID = data["PaymentTypeID"];
			//strIsPregnant = data["IsPregnant"] ? "1" : string.Empty;
			strRequestedDate.Text = data["requestedDate"].ToString();
			strRequestorName.Text = data["requestorName"].ToString();
			strPacientName = data["PacientName"].ToString();
			strPacientCNP = data["cnp"].ToString();
			pacientID = data["pacientID"].ToString();
			strMedicName = data["MedicName"].ToString();
			nrChitanta.Text = data["nrChit"].ToString();
			zonaChitanta.Visible = nrChitanta.Text.Length > 0;
			strPacientSection = data["SectionName"].ToString();
		}
		#endregion

		#region Determine if this is a re-print...
		string sqlDuplicat = @" select datediff(day,min(printdate),getdate()) as daydiff from LAB_REQUESTS_PRINT
			where requestid=" + intCodeID.Text;
		DataSet dsDuplicat = null;
		try
		{
			dsDuplicat = GetData(sqlDuplicat);
		}
		catch (SqlException ex)
		{
			AppendWarningMessage("Warning: Cannot determine previous print date <!-- " + sqlDuplicat + @" -->
				from the db: (" + ex.GetType().ToString() + ") " + ex.Message);
		}
		if ((dsDuplicat != null) && (dsDuplicat.Tables.Count > 0) && (dsDuplicat.Tables[0].Rows.Count > 0))
		{
			bDuplicat = true;
			object dateDiff = dsDuplicat.Tables[0].Rows[0][0];
			if (dateDiff != DBNull.Value)
			{
				int elapsedDays = System.Convert.ToInt32(dateDiff);
				bDuplicat = (elapsedDays > 2);
			}
		}
		else bDuplicat = false;
		#endregion

		#region Determine is this is a full print or not.
		bFullPrint = true;
		if (!string.IsNullOrEmpty(lstDomainID))
		{
			//toate domeniile care nu sunt selectate pentru printare. Daca exista cel putin unul se va considera tiparire partiala
			string sqlFullPrint = @" SELECT DISTINCT ld.id FROM analyses a
					LEFT JOIN machines m on m.id=a.machineid
					LEFT JOIN machine_types mt on m.typeid=mt.id
					LEFT JOIN lab_domains ld on mt.class=ld.domain
				WHERE a.requestid=" + intCodeID + @"
					AND ld.id not in
					(
						SELECT distinct ld.id FROM analyses a
							LEFT JOIN machines m on m.id=a.machineid
							LEFT JOIN machine_types mt on m.typeid=mt.id
							LEFT JOIN lab_domains ld on mt.class=ld.domain
						WHERE a.requestid=" + intCodeID + @"
							AND ld.id in (" + lstDomainID + @")
					)	";
			try
			{
				DataSet dsDomeniiExcluse = GetData(sqlFullPrint);
				//TODO? do something with this info! ;-)
				bFullPrint = dsDomeniiExcluse.Tables[0].Rows.Count == 0;
			}
			catch (SqlException ex)
			{
				AppendWarningMessage("Warning: Cannot determine print-disabled domains <!-- " + sqlFullPrint + @" -->
					from the db: (" + ex.GetType().ToString() + ") " + ex.Message);
			}
		}
		#endregion

		#region get user details
		string sqlUser = @" SELECT sectioncode, s.FirstName+' '+s.LastName + ISNULL(' - '+s.Title,'') as userName,
				CONVERT(varchar(20),GetDate(),113) as printDate
				FROM users u LEFT JOIN staff s on u.staffid=s.id
				WHERE u.login='" + Tools.userLogin + "'";
		DataSet dsUser = null;
		try
		{
			dsUser = GetData(sqlUser);
		}
		catch (SqlException ex)
		{
			AppendWarningMessage("Warning: Cannot get user details <!-- " + sqlDetails + @" -->
				from the db: (" + ex.GetType().ToString() + ") " + ex.Message);
		}
		if ((dsUser != null) && (dsUser.Tables.Count > 0) && (dsUser.Tables[0].Rows.Count > 0))
		{
			DataRow data = dsUser.Tables[0].Rows[0];
			//userSection = data["sectioncode"];
			userName.Text = data["userName"].ToString();
			CurrentDate.Text = data["printDate"].ToString();
		}
		else
		{
			userName.Text = "'" + Tools.userLogin + "'";
			CurrentDate.Text = DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"); //113, trimmed to first 20 chars
		}
		#endregion

		//labSectionCode = Session("Range") & "-LAB"

		if (bPrint && bFullPrint)
		{
			string[] paramNames = new string[] {"@RequestID", "@userLogin"};
			string[] paramValues = new string[] {intCodeID.Text, Tools.userLogin};
			ExecuteSiuiSP("LabRequest_MarkPrint", paramNames, paramValues);
			//Hipocrate.DB.DBConnection.Execute("LabRequest_MarkPrint", paramNames, paramValues);
		}

		DisplayResults();
	}

	/// <summary>
	/// Display analyse results, in printer format.
	/// </summary>
	private void DisplayResults()
	{
		string sqlResults = @" SELECT a.id, domain.Domain as DomainName, '' as newDomain, substring(lv.userlogin,6,len(lv.userlogin)) as staffvalidator, domain.printx as domainPrintX, ISNULL(domain.printY,1000) as domainPrintY, at.PrintExpanded as PrintExpanded,
			at.Name as AnalyseName, ISNULL(at.printY,1000) as analysePrintY, at.printX as analysePrintX, mt.AfisezPeBuletin,
			resultsCount=(select count(*) from results r  left join refs ref on r.refid=ref.id where ref.isprintable=1 and analyseid=a.id ), s.FirstName+' '+s.LastName + ISNULL(' - ' +s.Title,'') as Validator, mt.name as machineTypeName, Comment as analyseComment
				FROM analyses a
					LEFT JOIN analyse_Types at on a.typeid=at.id
					LEFT JOIN machine_types mt on at.machinetypeid=mt.id
					LEFT JOIN lab_domains domain on domain.domain=mt.class
					LEFT JOIN lab_validated lv on a.requestid=lv.requestid and domain.id=lv.domainid
					LEFT JOIN users u on u.login=lv.userlogin
					LEFT JOIN staff s on u.staffid=s.id
				WHERE a.requestid=" + intCodeID.Text;
		if (!string.IsNullOrEmpty(strClass))
			sqlResults += " and domain.domain in ('" + strClass + "')";
		if (!string.IsNullOrEmpty(lstDomainID))
			sqlResults += " and domain.id in (" + lstDomainID + ")";
		sqlResults += "	ORDER BY domainPrintY, DomainName, analysePrintY, analyseName";

		displayedResults.ItemDataBound += new RepeaterItemEventHandler(displayedResults_ItemDataBound);
		try
		{
			DataSet dsResults = GetData(sqlResults);
			ComputeNewDomainColumn(dsResults);
			closeLastDomain.Visible = dsResults.Tables[0].Rows.Count > 0;
			displayedResults.DataSource = dsResults;
			displayedResults.DataBind();
			test.DataSource = dsResults;
			test.DataBind();
			CloseLastDomain();
		}
		catch (SqlException ex)
		{
			AppendWarningMessage("Warning: Cannot get data <!-- " + sqlResults + @" -->
				from the db: (" + ex.GetType().ToString() + ") " + ex.Message);
		}
		lastDomainCount = domainCount + 1;
	}

	void ComputeNewDomainColumn(DataSet data)
	{
		if ((data == null) || (data.Tables.Count == 0))
			return;
		int nRows = data.Tables[0].Rows.Count;
		if (nRows == 0) return;
		data.Tables[0].Columns["newDomain"].ReadOnly = false;
		data.Tables[0].Rows[0]["newDomain"] = "*";
		for (int r = 1; r < nRows; ++r)
			if (!data.Tables[0].Rows[r]["DomainName"].Equals(data.Tables[0].Rows[r-1]["DomainName"]))
				data.Tables[0].Rows[r]["newDomain"] = "*";
	}

	private string cumulatedDomainComments = "";
	protected int domainCount = 0;
	private int resultCount = 0, oldResultCount = 0;
	void displayedResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		DataRowView data = e.Item.DataItem as DataRowView;
		bool isNewDomain = data["newDomain"].ToString().Length > 0,
			isValidated = data["staffvalidator"].ToString().Length > 0;
		#region new domain
		e.Item.FindControl("newDomain").Visible = isNewDomain; // && isValidated;
		if (isNewDomain)
		{
			e.Item.FindControl("closePreviousDomain").Visible = domainCount > 0;
			if (cumulatedDomainComments.Length > 0)
			{
				e.Item.FindControl("domainCommentsArea").Visible = true;
				(e.Item.FindControl("domainCommentsText") as Label).Text = cumulatedDomainComments;
				cumulatedDomainComments = "";
			}
			++domainCount;
			//(e.Item.FindControl("domainCountOutput1") as Literal).Text = domainCount.ToString();
			string pageBreakDecision = (domainCount != 1 ? "always" : "auto");
			//(e.Item.FindControl("pageBreakDecision") as Literal).Text = pageBreakDecision;
			(e.Item.FindControl("domainTableContainer") as Literal).Text = @"<p id=""P" + domainCount + @""" style=""page-break-before: " + pageBreakDecision + @""" >";
			(e.Item.FindControl("domainTableID") as Literal).Text = @"id=""D" + domainCount.ToString() + '"';

			if (!isValidated)
				(e.Item.FindControl("domainDisplayClass") as Literal).Text = "class='tdnplusleftDisabled'";

			(e.Item.FindControl("domainName") as Literal).Text = data["DomainName"].ToString();
			Literal validationInfo = e.Item.FindControl("validationInfo") as Literal;
			if (isValidated)
				validationInfo.Text = " - Validat de : " + data["staffvalidator"].ToString();
			else
				validationInfo.Text = " - NEVALIDAT ";
		}
		#endregion

		(e.Item.FindControl("analyseID") as Literal).Text = data["id"].ToString();

		bool bForceDomainHeader = false;
		if (data["staffvalidator"].ToString().Length > 0)
		{
			if (isNewDomain)
				bForceDomainHeader = true;

			if (resultCount != 0)
				oldResultCount = resultCount;
		}
		resultCount = System.Convert.ToInt32(data["resultsCount"]);
		bForceDomainHeader |= (oldResultCount != resultCount);
		if ((resultCount != 0) && (data["analyseComment"].ToString().Length > 0))
		{
			string analyseComment = "<br/><b>*" + data["analyseName"].ToString() + ":</b> " + data["analyseComment"].ToString();
			cumulatedDomainComments += analyseComment.Replace(" ", "&nbsp;");
		}

		Repeater rezultateAnaliza = e.Item.FindControl("rezultateAnaliza") as Repeater;
		rezultateAnaliza.ItemDataBound += new RepeaterItemEventHandler(rezultateAnaliza_ItemDataBound);

		//(e.Item.FindControl("repeatingOutput") as Literal).Text = data["PrintExpanded"].ToString() + "__";
		//	if  (data["analysePrintX"]="") then ' if  (data["PrintExpanded"]<>"true") then
		//		if (bForceDomainHeader)
		if (!"true".Equals(data["PrintExpanded"]) && (resultCount < 2) && (data["staffvalidator"].ToString().Length > 0))
		#region few results
		{
			if ((resultCount > 0) && isNewDomain)
			{
				e.Item.FindControl("analyseTableHeader").Visible = true;
				bForceDomainHeader = false;
			}
			string sqlTheOneResult = @" select refs.name as refName,IsNull(StringValue, 0) as StringValue,MinValue,MaxValue,um.name as umName,ISNULL(refs.PrintY,1000) as PrintY
					,1 as AfisezPeBuletin, '' as machineTypeName
				from results r
				left join analyses a on a.id=r.analyseid
				left join refs on refs.id=r.refid AND REFS.ISPRINTABLE=1
				left join um on refs.umid=um.id
				left join lab_requests lr on a.requestid=lr.id ";
			//	sqlResults += "					join lab_validated lv on lv.requestid=lr.id ";
			sqlTheOneResult += @"		left join pacients p on lr.pacientid=p.id
				left join REF_NORMAL_VALUES rnv on r.refid=rnv.refid and p.sex=rnv.sex ";
			//	sqlResults += "					join lab_validated lv on lv.requestid=lr.id ";
			//sqlResults += "				and datediff(year,p.birthdate,GetDate()) between rnv.ageLo and rnv.ageHi ";
			sqlTheOneResult += @"			AND	Datediff(year,p.BirthDate,GetDate()) >= rnv.ageLo and Datediff(year,p.BirthDate,GetDate()) < rnv.ageHi
				where r.analyseid=" + data["id"].ToString() +
					" order by printy,refs.name";

			(e.Item.FindControl("repeatingOutput") as Literal).Text += "<!--" + sqlTheOneResult + "-- >";

			DataSet dsTheOneResult = GetData(sqlTheOneResult);
			if (dsTheOneResult.Tables[0].Rows.Count > 0)
			#region fill out and show table row 'trTheOneResult'
			{
				/*
				e.Item.FindControl("trTheOneResult").Visible = true;
				(e.Item.FindControl("AnalyseName2") as Literal).Text = data["AnalyseName"].ToString();
				e.Item.FindControl("AfisezPeBuletin2").Visible = "True".Equals(data["AfisezPeBuletin"]);
				(e.Item.FindControl("machineTypeName2") as Literal).Text = data["machineTypeName"].ToString();

				DataRow result = dsTheOneResult.Tables[0].Rows[0];
				string displayed = result["StringValue"].ToString();
				double value;
				if (double.TryParse(displayed, out value))
					displayed = value.ToString("N2"); //or: "0.00"
				(e.Item.FindControl("StringValue") as Literal).Text = displayed;

				double minValue, maxValue;
				if (double.TryParse(displayed, out value) && double.TryParse(result["minValue"].ToString(), out minValue) && double.TryParse(result["maxValue"].ToString(), out maxValue))
				{
					e.Item.FindControl("tooLow").Visible = value < minValue;
					e.Item.FindControl("tooHigh").Visible = value > maxValue;
				}

				Literal intervalDisplay = e.Item.FindControl("interval") as Literal;
				intervalDisplay.Text = result["MinValue"].ToString();
				if (intervalDisplay.Text.Length > 0) intervalDisplay.Text += " - ";
				intervalDisplay.Text += result["maxValue"].ToString();
				if (result["umName"].ToString().Length > 0)
					(e.Item.FindControl("umName") as Literal).Text = " / " + result["umName"].ToString();
				*/
				//update the dataset:
				dsTheOneResult.Tables[0].Columns["refName"].ReadOnly = false;
				dsTheOneResult.Tables[0].Columns["AfisezPeBuletin"].ReadOnly = false;
				dsTheOneResult.Tables[0].Columns["machineTypeName"].ReadOnly = false;
				foreach (DataRow r in dsTheOneResult.Tables[0].Rows)
				{
					r["refName"] = data["AnalyseName"];
					r["AfisezPeBuletin"] = "True".Equals(data["AfisezPeBuletin"]);
					r["machineTypeName"] = data["machineTypeName"];
				}
				rezultateAnaliza.DataSource = dsTheOneResult;
				rezultateAnaliza.DataBind();
			}
			#endregion
		}
		#endregion
		if ((resultCount > 1) || ("true".Equals(data["PrintExpanded"]) && (resultCount > 0)))
			if (isValidated) //&& isNewDomain)
		{
			e.Item.FindControl("analyseHeaderWide").Visible = true;
			/**/(e.Item.FindControl("analyseID") as Literal).Text += " said to be validated...";
			e.Item.FindControl("analyseTableHeader").Visible = true;
			(e.Item.FindControl("AnalyseName") as Literal).Text = data["AnalyseName"].ToString();
			e.Item.FindControl("AfisezPeBuletin").Visible = "True".Equals(data["AfisezPeBuletin"]);
			(e.Item.FindControl("machineTypeName") as Literal).Text = data["machineTypeName"].ToString();
			bForceDomainHeader = false;
			string sqlAllResults = @" select distinct refs.ScreenY, refs.name as refName,IsNull(StringValue, 0) as StringValue,MinValue,MaxValue,um.name as umName
					,0 as AfisezPeBuletin, '' as machineTypeName
				from results r
				left join analyses a on a.id=r.analyseid
				left join refs on refs.id=r.refid
				left join um on refs.umid=um.id
				left join lab_requests lr on a.requestid=lr.id
					join lab_validated lv on lv.requestid=lr.id
				left join pacients p on lr.pacientid=p.id
				left join REF_NORMAL_VALUES rnv on r.refid=rnv.refid and p.sex=rnv.sex";
			//sqlAllResults += "				and datediff(year,p.birthdate,GetDate()) between rnv.ageLo and rnv.ageHi";
			sqlAllResults += @"			AND	Datediff(year,p.BirthDate,GetDate()) >= rnv.ageLo and Datediff(year,p.BirthDate,GetDate()) < rnv.ageHi
				where r.analyseid=" + data["id"].ToString() + @"
					and refs.isprintable=1
				ORDER BY refs.ScreenY ASC";

			(e.Item.FindControl("repeatingOutput") as Literal).Text += "<!--" + sqlAllResults + "-- >";
			DataSet dsAllResults = GetData(sqlAllResults);
			rezultateAnaliza.DataSource = dsAllResults;
			rezultateAnaliza.DataBind();
		}
	}

	void rezultateAnaliza_ItemDataBound(object sender, RepeaterItemEventArgs e)
	{
		DataRowView data = e.Item.DataItem as DataRowView;
		(e.Item.FindControl("RefName") as Literal).Text = data["refName"].ToString();
		e.Item.FindControl("AfisezPeBuletin").Visible = "True".Equals(data["AfisezPeBuletin"]);
		(e.Item.FindControl("machineTypeName") as Literal).Text = data["machineTypeName"].ToString();

		string displayed = data["StringValue"].ToString();
		double value;
		if (double.TryParse(displayed, out value))
			displayed = value.ToString("N2"); //or: "0.00"
		(e.Item.FindControl("StringValue") as Literal).Text = displayed;

		double minValue, maxValue;
		if (double.TryParse(displayed, out value) && double.TryParse(data["minValue"].ToString(), out minValue) && double.TryParse(data["maxValue"].ToString(), out maxValue))
		{
			e.Item.FindControl("tooLow").Visible = value < minValue;
			e.Item.FindControl("tooHigh").Visible = value > maxValue;
		}

		Literal intervalDisplay = e.Item.FindControl("interval") as Literal;
		intervalDisplay.Text = data["MinValue"].ToString();
		if (intervalDisplay.Text.Length > 0) intervalDisplay.Text += " - ";
		intervalDisplay.Text += data["maxValue"].ToString();
		if (data["umName"].ToString().Length > 0)
			(e.Item.FindControl("umName") as Literal).Text = " / " + data["umName"].ToString();
	}

	private void CloseLastDomain()
	{
		if (cumulatedDomainComments.Length > 0)
		{
			lastDomainCommentsArea.Visible = true;
			lastDomainCommentsText.Text = cumulatedDomainComments;
			cumulatedDomainComments = "";
		}
	}

	private DataSet GetData(string sql)
	{
		return Hipocrate.DB.DBConnection.GetData(sql);
		//Hipocrate.DB.DBConnection.VariableConnectionString = ConfigurationManager.ConnectionStrings["SIUI"].ConnectionString;
		//return Hipocrate.DB.DBConnection.GetDataVar(sql);
	}

	private int ExecuteSiuiSP(string spName, string[] paramNames, object[] paramValues)
	{
		SqlConnection connection = null;
		try
		{
			connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SIUI"].ConnectionString);
			connection.Open();

			SqlCommand cmd = connection.CreateCommand();
			cmd.CommandType = CommandType.StoredProcedure;
			cmd.CommandText = spName;
			for (int i = 0; i < paramNames.Length; ++i)
				cmd.Parameters.AddWithValue(paramNames[i], paramValues[i]);

			return cmd.ExecuteNonQuery();
		}
		finally
		{
			if (connection != null)
				connection.Close();
		}
	}
}
